import React from 'react';
import {connect} from 'react-redux';
import {Avatar, Badge, Card, Col, Icon, Row, Spin, Tabs, Radio, Button, Alert, Modal, Popover} from 'antd';
const TabPane = Tabs.TabPane;
const {Meta} = Card;
import noInfo from "images/no-info.png";
import menuRoute from "routes/menuRoute";
import {messages} from "share/common";
import 'styles/new-sub-application/sub-application.scss'
import PreviewModal from 'containers/new-sub-application/preview-modal'
import subApplicationService from "containers/new-sub-application/new-sub-application.service";
import SlideFrame from "components/slide-frame";
import SeniorSetting from 'containers/new-sub-application/senior-setting';
import  subApplicationInfo from 'containers/setting/sub-application/sub-application-management/sub-application-info'
import  editSubApplication from 'containers/setting/sub-application/sub-application-management/edit-sub-application'

class SubApplicationIndex extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      activeKey: "1",
      cloudEnvOptions: [],
      subModule: [],
      data: [],
      visible: false,
      appVisible: false,
      sectionName: "",
      subList: [],
    };
  }

  componentWillMount() {
    this.getSubModule();
  }

  onTabChange = (activeKey) => {
    this.setState({
      activeKey,
    }, () => {
      this.getSubAppList();
    })
  };

  getSubModule = () =>{
    this.setState({
      loading: true,
    });
    subApplicationService.getSubModule().then(res => {
      if(res.data && res.data.length) {
        this.setState({
          loading: false,
          subModule: res.data,
          activeKey: res.data[0].moduleId,
        }, () => {
          this.getSubAppList();
        })
      }
    }).catch(err => {
    });
  };


  getSubAppList = () =>{
    const {activeKey} = this.state;
    this.setState({
      loading: true,
    });
    subApplicationService.getSubAppList(activeKey).then(res => {
      if(res && res.data) {
        if(activeKey === "1"){
          let arr = res.data.filter(item => item.sectionCode === "THIRD_PARTY");
          if(!arr.length){
            res.data.push(
              {sectionName: messages('basic-9.key70')/*第三方应用*/, sectionCode: "THIRD_PARTY", tenantWidgetDetail: []})
          }
        }
        this.setState({
          loading: false,
          data: res.data,
        })
      }
    }).catch(err => {
      this.setState({
        loading: false,
      });
    });
  };

  renderBasicSettingSlide = (config) => {
    let {title, content, params} = config;
    return {
      title,
      content,
      params,
      afterClose: this.afterClose,
    }
  };

  afterClose = () => {
    this.getSubAppList();
  };

  //跳转到新建子应用页
  createSubApplication = (item, card) => {
    if(card.sectionCode !== "THIRD_PARTY"){
      if(item.appCode){
        this.goEditSubApplication("", item, card)
      }else {
        this.getSectionList(card);
      }
    }else {
      let title = item.id ? messages('basic-9.key111')/*编辑应用*/ : messages('basic-9.key119')/*新建应用*/,
        params = {id: item.id};
      let config = {title, content: subApplicationInfo, params};
      SlideFrame.open(this.renderBasicSettingSlide(config), this);
    }
  };

  //跳转到新建子应用页
  goEditSubApplication = (e, param, card) => {
    const {activeKey} = this.state;
    this.setState({
      appVisible: false
    }, () => {
    let title = param.appCode ? messages('basic-9.key111')/*编辑应用*/ : messages('basic-9.key119')/*新建应用*/,
      params = {
        appCode: param.appCode,
        sectionCode: card ? card.sectionCode : (param.source === 'VENDOR' ? 'VENDOR': null ),
        appName: param.appName,
        appDesc: param.appDesc,
        activeKey,
      };
      let config = {title, content: editSubApplication, params};
      SlideFrame.open(this.renderBasicSettingSlide(config), this);
    });
  };

  onRadioChange = (e, child) => {
    let {data} = this.state;
    child.checked = e.target.value;
    this.setState({
      data,
    });
  };

  //跳转到高级设置
  goSubApplicationLayoutSetting = (e) => {
    let {activeKey} = this.state;
    if(activeKey === "1"){
      this.context.router.push(menuRoute.getPageUrlByKey('sub-application-layout-setting'))
    } else{
      SlideFrame.open({
        title: messages('basic-9.key69')/*高级设置*/,
        content: SeniorSetting,
        params: {activeKey: activeKey,}
      }, this)
    }
  };

  //渲染主界面
  renderApplicationCategory() {
    const {data, loading} = this.state;
    return (
      <div>
        <Spin spinning={loading}>
          <div className="sub-application">
            {
              data && data.length ?
                data.map((category, index) =>{
                 return (
                   <div key={category.sectionCode}>
                     <Row type="flex"
                          justify="start"
                          align="middle"
                          style={{background: '#eee', padding: 10, marginBottom: 20}}>
                       <Col span={24}>
                        <span style={{fontSize: 16, fontWeight: 700, color: '#656565'}}>
                          {category.sectionName}
                        </span>
                       </Col>
                     </Row>
                     {this.renderApplicationList(category)}
                   </div>
                 )})
                : null
            }
          </div>
        </Spin>
      </div>
    )
  }

  renderApplicationList(card) {
    return (
      <Row gutter={16}>
        {
          card.tenantWidgetDetail && card.tenantWidgetDetail.length ?
            card.tenantWidgetDetail.map((item, index) =>
              <Col span={5} style={{marginBottom: 20}} key={item.id}
                   onClick={() => this.createSubApplication(item, card)}>
                <Card hoverable={true} style={{borderRadius: 5, height: 70}} bodyStyle={{padding: "0 0 0 20px"}}>
                  <Meta
                    avatar={(
                      <div>
                        {item.appIcon && (
                          <Avatar size="large" src={item.appIcon}/>
                        )}
                        {!item.appIcon && (
                          <Avatar size="large" src={noInfo}/>
                        )}
                      </div>
                    )}
                    description={(
                      <div>
                        <span className="card-description">
                          {item.appName}&nbsp;
                          {
                            item.appRemark &&
                              <Popover content={item.appRemark}>
                                <Icon type="info-circle-o" style={{cursor: "pointer", color: "rgba(0,0,0,0.35)"}}/>
                              </Popover>
                          }
                        </span>
                        <Badge status={item.enabled ? 'success' : 'error'}
                               text={item.enabled ?
                                 messages('basic-9.key47')/*启用temp*/
                                 : messages('basic-9.key71')/*禁用temp*/}/>
                      </div>
                    )}
                  />
                </Card>
              </Col>
            )
            : null

        }
        {
          (<Col span={5}
                style={{marginBottom: 20}}
                onClick={() => {this.createSubApplication({}, card)}}>
            <Card hoverable={true}
                  bodyStyle={{padding: 24}}
                  style={{borderRadius: 5, height: 70, borderStyle: 'dashed'}}>
              <Row type="flex" justify="center" align="middle" style={{color: '#0092da'}}>
                <Col span={24} style={{textAlign: 'center'}}>
                  <Icon type="plus"/>
                  <span>
                    {
                      card.sectionCode === "THIRD_PARTY" ?
                        messages('basic-9.key72')/*新增应用*/ :
                        messages('basic-9.key73')/*从应用列表中选择*/
                    }
                    &nbsp;
                  </span>
                </Col>
              </Row>
            </Card>
          </Col>)
        }

      </Row>
    );
  }

  //管理端 获取当前租户下对应section可用列表
  getSectionList = (item) => {
    this.setState({
      loading: true,
    });
    this.setState({
      appVisible: true,
      sectionName: item.sectionName,
    });
    subApplicationService.getSectionList(item.sectionCode).then(res => {
      this.setState({
        subList: res.data,
        loading: false,
      })
    }).catch(err => {
      this.setState({
        loading: false,
      });
    })
  };

  goPage = () => {
    window.open("/main/permission-setting/role-menu-setting")
  };

  render() {
    const {activeKey, subModule, visible, data, appVisible, sectionName, loading, subList} = this.state;
    let {menuTree} = this.props;
    let role = menuTree.allAPIMenuItem["role-menu-setting"];
    let text = {
      "1": messages('basic-9.key120')/*应用*/,
      "2": messages('basic-9.key21')/*首页*/,
      "3": messages('basic-9.key22')/*我的*/,
    };
    let info = <span>
      {messages('basic-9.key127')/*设置后将对移动端生效，功能权限配置请前往：*/}
        <a onClick={this.goPage}>
          {role ? role.resourceName :  messages('basic-9.key122')/*角色维护*/}
        </a>
    </span>;
    return (
      <Spin spinning={loading}>
        <Alert message={info} type="info" showIcon/>
        {
          subModule.length ?
            <div>
              <Tabs style={{fontSize: 18}} activeKey={activeKey} onChange={this.onTabChange}>
                {
                  subModule.map((item) => {
                    return (
                      <TabPane key={item.moduleId} tab={item.moduleName}/>
                    )
                  })
                }
              </Tabs>
              <div className="bottom-gap">
                <span>
                  {messages('basic-9.key123',{arg1: text[activeKey]})/*以下启用的应用，会出现在App-{arg1}*/}
                  {
                    activeKey === "1" &&
                    <Button
                      type={'primary'}
                      ghost
                      size={'small'}
                      onClick={() => {
                        this.setState({visible: true})
                      }}
                      style={{marginLeft: 10}}>{messages('basic-9.key68')/*预览*/}
                    </Button>
                  }
                </span>
                {
                  activeKey !== "2" &&
                  <span onClick={this.goSubApplicationLayoutSetting} style={{position: "absolute", right: 20}}>
                    <a>{messages('basic-9.key69')/*高级设置*/}<Icon type="right"/></a>
                  </span>
                }
              </div>
              {this.renderApplicationCategory()}
            </div>
            :
            null
        }
        {
          data && data.length ?
            <PreviewModal visible={visible} onCancel={() => {this.setState({visible: false})}} data={data}/>
            : null
        }
        <Modal onCancel={() => {this.setState({appVisible: false})}}
               getPopupContainer={() => document.getElementsByClassName('sub-application')[0]}
               footer={null}
               width={620}
               visible={appVisible}
               title={sectionName}>
          { loading ?
            <Spin spinning={loading}/>
            :
            <div>
              {subList && subList.length ?
                <Row gutter={16}>
                  {subList.map((param, index) => {
                    return (
                      <Col span={12}
                           style={{marginBottom: 20}}
                           key={index}
                           onClick={(e) => this.goEditSubApplication(e, param)}>
                        <Card hoverable={true}
                              style={{borderRadius: 5, height: 70}}
                              bodyStyle={{padding: 18}}>
                          <Meta
                            avatar={(
                              <div>
                                {param.appIcon && (
                                  <Avatar size="large"
                                          src={param.appIcon}
                                          style={{background: 'none'}}/>
                                )}
                                {!param.appIcon && (
                                  <Avatar size="large"
                                          src={noInfo}
                                          style={{background: 'none'}}/>
                                )}
                              </div>
                            )}
                            description={(
                              <div>
                                <div className="card-description">
                                  {param.appName}&nbsp;
                                  {
                                    param.appRemark ?
                                      <Popover content={param.appRemark}>
                                        <Icon type="info-circle-o"
                                              style={{cursor: "pointer", color: "rgba(0,0,0,0.35)"}}/>
                                      </Popover>
                                      : null
                                  }
                                </div>
                                {
                                  param.tenantWidget && param.tenantWidget.hasOwnProperty("enabled") ?
                                    <span style={{fontSize: 12}}>
                                    <Badge status={param.tenantWidget.enabled ? 'success' : 'error'}
                                           text={param.tenantWidget.enabled ? messages('basic-9.key47')/*启用temp*/ :
                                             messages('basic-9.key71')/*禁用temp*/}/>
                                  </span>
                                    : null
                                }
                              </div>
                            )}
                          />
                        </Card>
                      </Col>
                    )
                  })
                  }
                </Row>
                :
                <div>{messages('basic-9.key124')/*暂无可选择的应用*/}</div>
              }
            </div>
          }
        </Modal>
      </Spin>
    )
  }

}

SubApplicationIndex.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    subAppCloudTab: state.cache.subAppCloudTab,
    subAppCurrentTab: state.cache.subAppCurrentTab,
    menuTree: state.login.menuTree,
  }
}

export default connect(mapStateToProps)(SubApplicationIndex);
